package chapter9_instant;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


//动态代理
public class P91 {
    interface IHello{
        void sayHello();
        void sayHello1();
    }

    static class Hello implements IHello{
        @Override
        public void sayHello() {
            System.out.println("hello proxy");
        }

        @Override
        public void sayHello1() {
            System.out.println("hello proxy1");
        }
    }

    static class DynamicProxy implements InvocationHandler{
        public Object oldObj;

        public Object bind(Object obj){
            this.oldObj = obj;
            return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),this);
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("呵呵哒");
            return method.invoke(oldObj,args);
        }
    }
    public static void main(String[] args) throws FileNotFoundException {
        //把生成出来的代理文件二进制流的代码copy保存一份在文件中
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
//        FileOutputStream file = new FileOutputStream("$Proxy0" + ".class");
//        System.out.println(new File("$Proxy0" + ".class").getAbsolutePath());
        DynamicProxy dynamicProxy = new DynamicProxy();
//        IHello hello = (IHello) dynamicProxy.bind(new Hello());
//        new Class[]{IHello.class} 79 +63  90+80+150+202= 522-140= 380 + 220 +100=700  3254 +700 =3954

        IHello hello1 = (IHello) Proxy.newProxyInstance(IHello.class.getClassLoader(),new Class[]{IHello.class} , new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("heheda");
                return null;
            }
        });
        hello1.sayHello();
        hello1.toString();
        hello1.hashCode();
//        hello.sayHello();

    }

}
